import api from '@/odoorpc'

const Mixin = {
  data() {
    const database = process.env.VUE_APP_ODOO_DB

    const base_api = process.env.VUE_APP_BASE_API

    const username = base_api === '/dev-api' ? 'admin' : 'admin'
    const password = base_api === '/dev-api' ? '123456' : '123456'
    const verificationCode = ''

    let checkCode = (rule, value, callback) => {
      console.log(typeof this.codeNum)
      console.log(typeof value)

      if (value.length < 4 && value) {
        callback(new Error('验证码为4位'))
      } else if (value !== String(this.codeNum)) {
        callback(new Error('请输入正确的验证码'))
      } else {
        callback()
      }
    }

    return {
      codeNum: '',
      form2: {
        database,
        username,
        password,
        verificationCode
      },

      database_options: [],

      rules: {
        database: [
          {
            required: true,
            message: 'Please select database!',
            trigger: ['change', 'blur']
          }
        ],
        username: [
          {
            required: true,
            message: 'Please input your username!',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: 'Please input your password!',
            trigger: 'blur'
          }
        ],
        verificationCode: [
          { validator: checkCode, trigger: 'blur' } //自定义检验
        ]
      }
    }
  },
  computed: {
    login_rules() {
      return {
        database: [{ required: true, message: '密码不能为空' }],
        username: [{ required: true, message: '账号不能为空' }],
        password: [{ required: true, message: '密码不能为空' }]
      }
    }
  },
  async created() {},

  methods: {
    async init() {
      // const db = process.env.VUE_APP_ODOO_DB
      const dbs = await api.web.database.list()
      // this.database_options = dbs.filter(item => (db ? item === db : true))
      this.database_options = dbs
    },

    async handleLogin(values, success, error) {
      try {
        const info = await api.web.login({
          db: values.database,
          login: values.username,
          password: values.password
        })

        // const { session } = info
        // const User = api.env.model('res.users')
        // const uid = session.uid
        // const fields = ['name', 'email']
        // const user = await User.read(uid, { fields })
        // console.log(user)

        if (success) {
          success(info)
        }
      } catch (e) {
        console.log(e)
        if (error) {
          error(e)
        }
      }
    },
    // 随机生成四位数
    rand(min, max) {
      return Math.floor(Math.random() * (max - min)) + min
    },
    getCodeNum() {
      this.codeNum = this.rand(1000, 9999)
    }
  }
}

export default Mixin
